
<script setup lang="ts">
import {ref,onMounted, onBeforeUnmount } from 'vue';

const startTime = ref<number>(0); // 记录开始时间
const stayDuration = ref<number>(0); // 记录停留时长
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
  stayDuration.value = Date.now() - startTime.value;
  console.log(`用户停留时间: ${stayDuration.value / 1000} 秒`);
  console.log(11111111111)
  // 阻止默认行为并触发微信浏览器默认的提示框
  event.preventDefault();
  event.returnValue = ''; // 空字符串触发默认提示
};

onMounted(() => {
  startTime.value = Date.now();
  // 监听窗口关闭或刷新事件
  window.addEventListener('beforeunload', handleBeforeUnload);
});

onBeforeUnmount(() => {
  // 组件卸载时移除事件监听
  window.removeEventListener('beforeunload', handleBeforeUnload);
});
</script>

<template>
  <div>
    <p>微信浏览器关闭窗口或刷新时弹出提示</p>
  </div>
</template>

